import pika
import time
import json
from base_restful.order import *
from .util_def import get_uuid, get_time_str
from .const import BaseInfo

__connection = None


def __get_conn():
    global __connection

    if __connection is not None:
        return __connection

    print('初始化mq链接：host:' + BaseInfo.get_mq_config()['host'] + 'vhost:' + BaseInfo.get_mq_config()['vhost'])
    credentials = pika.PlainCredentials("cluster-ms-cmall", "cluster-ms-cmall")
    parameters = pika.ConnectionParameters(host=BaseInfo.get_mq_config()['host'],
                                           virtual_host=BaseInfo.get_mq_config()['vhost'], credentials=credentials)
    __connection = pika.BlockingConnection(parameters)
    return __connection

"""
测试环境使用mq模拟发送，会造成数据的断档，目前只适用于开发环境制造数据
"""


def send_stockout_all(order_id):
    orderInfo = get_order_details(order_id)['data']
    details = list(orderInfo['orderMainDetailList'])
    ck_id = 'CKPY_' + get_uuid(10)

    m = {"orderId": order_id, "outId": ck_id, "type": 0, "outTime": get_time_str()}

    channel = __get_conn().channel()

    ck_details = []
    for d in details:
        ck_details.append({"orderId": order_id, "goodsId": d['goodsId'], "name": d['name'], "quantity": d['quantity']})

    m['goodsInfo'] = ck_details

    print(m)
    channel.basic_publish(exchange='exchanges.phoenix.erp',
                          routing_key='routing.phoenix.erp.order.stock.out',
                          body=json.dumps(m, ensure_ascii=False))
    channel.close()


def send_all_return_in(order_id):
    r = []
    wait_in_list = list(get_return_wait_stock_in_list_by_order_id(order_id))
    channel = __get_conn().channel()
    for return_item in wait_in_list:
        param = {"orderId": order_id, "returnId": return_item['returnOrderId'], "reason": ""}
        goods_list = []
        return_info = get_return_detail_return_id(return_item['returnOrderId'])
        for detail in return_info['details']:
            goods_list.append(
                {"goodsId": detail['goodsId'], "supplierId": "56d92458e7694a8d85aa2677d3e1b46d", "supplierName": "李少",
                 "receiveNum": detail['applyQuantity'], "qcPassNUm": detail['applyQuantity'], "concessionNum": 0})

        param['goodsList'] = goods_list
        channel.basic_publish(exchange='exchanges.phoenix.erp',
                              routing_key='routing.phoenix.erp.order.return.result',
                              body=json.dumps(param, ensure_ascii=False).encode("utf-8"))
        r.append(param)

    channel.close()

    return r
